//
//  ViewFormController.m
//  MClient
//
//  Created by  史正烨 on 09-10-20.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "ViewFormController.h"
#import "MServerDAO.h"
#import "MClientAppDelegate.h"
#import "MCFunction.h"
#import "MCUIToolkit.h"
#import "MCImageView.h"
#import "UIImageAdditions.h"
#import <QuartzCore/QuartzCore.h>
#import "MCSectionBar.h"
#import "WithFormButtonsBar.h"
#import "ProductViewAddition.h"

@interface ViewFormController (Private)
//int actionSheetFlag;
- (void) createRightBarButton;
- (void)onFormSelected:(int)index;
- (void) setLookupBackFillByFieldName: (NSString *)fieldName fieldDataLookupBack:(NSMutableDictionary *)fieldDataLookupBack;
@end

@implementation ViewFormController
@synthesize dataObjectName;
@synthesize layoutName;
@synthesize keyValue;
@synthesize initialValues;
@synthesize formData;
@synthesize formLayout;

#pragma mark ---- UIViewController方法 ----


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	
	[super viewDidLoad];
	
	tabIndex = 0;
	formLayoutCopy = [[MCUIToolkit getObjectCopy:formLayout] retain];
	
	[self leftBarButton:@"返回" withStyle:UIBarButtonItemStylePlain selector:@selector(selectCancelAction:)];
	self.title = [formLayoutCopy objectForKey:@"lbl"];
	
	// 设置帮助按钮
	self.addHelpButton = YES;
	self.helpUrl = @"/iphone/help/chapter05-02.html";
	
	// 图片下载并加载完成，返回图片尺寸信息
	imageSizeMap = [[NSMutableDictionary alloc] init];
	
	isSectionTab = NO;
	// 生成表单切换按钮
	if ([[formLayoutCopy objectForKey:@"slc"] count] > 0) {
		self.tableview.frame = CGRectMake(0, nToolBarHeight, self.width, self.height-nToolBarHeight);
		MCSectionBar *sectionBar = [[MCSectionBar alloc] initWithFrame:CGRectMake(0, 0, self.width, nToolBarHeight)];
		sectionBar.autoresizingMask = nMCViewAutoresizingMask;
		sectionBar.tag = -321;
		[sectionBar addSectionBar:[formLayoutCopy objectForKey:@"lbl"] withItems:[formLayoutCopy objectForKey:@"slc"] delegate:self];
		[self.clientView addSubview:sectionBar];
		[sectionBar release];
	} else if ([@"1" isEqualToString:[formLayoutCopy objectForKey:@"style"]] && [[formLayoutCopy objectForKey:@"stn"] count] > 1) {
		isSectionTab = YES;
		self.tableview.frame = CGRectMake(0, nToolBarHeight, self.width, self.height-nToolBarHeight);
		MCSectionBar *sectionBar = [[MCSectionBar alloc] initWithFrame:CGRectMake(0, 1, self.width, nToolBarHeight)];//huotianjun 以前是(0, 0, self.width, nToolBarHeight),结果显示下卷，我没有改过呀？是ios5的问题？
		sectionBar.autoresizingMask = nMCViewAutoresizingMask;
		sectionBar.tag = -321;
		[sectionBar addSectionBarItems:[formLayoutCopy objectForKey:@"stn"] delegate:self];
		[self.clientView addSubview:sectionBar];
		[sectionBar release];
	}
	
	
	
	buttonCol = 1;
	if ([formLayoutCopy objectForKey:@"csty"]) {
		if ([[formLayoutCopy objectForKey:@"csty"] objectForKey:@"button_col"]) {
			buttonCol =  [[[formLayoutCopy objectForKey:@"csty"] objectForKey:@"button_col"] intValue];
			if (buttonCol > 3) {
				buttonCol = 3;
			}
		}
		//根据扩展属性，设置uitableview的分割线
		self.separator = ![[[formLayoutCopy objectForKey:@"csty"] objectForKey:@"noseparatorline"] intValue];
	}
}

- (void)viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];
	
	[self didRotateFromInterfaceOrientation:0];
	[[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector(getImageSize:)
												 name:@"ImageSize" object:nil];
	
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
	[[NSNotificationCenter defaultCenter] removeObserver:self 
													name:@"ImageSize" 
												  object:nil];	
}

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
	[super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
	
	if ([[formLayoutCopy objectForKey:@"slc"] count] > 0 || isSectionTab) {
		self.tableview.frame = CGRectMake(0, nToolBarHeight, self.width, self.height-nToolBarHeight);
	} else {
		self.tableview.frame = CGRectMake(0, 0, self.width, self.height);
	}
	if (tabIndex > 0) {
		[self onFormSelected:tabIndex];
	} else {
		[self.tableview reloadData];
	}
	int withFormButtonsBarHeight = [MCUIToolkit getWithFormButtonsBarHeight:withFormButtons buttonCol:buttonCol];
	if (withFormButtonsBarHeight != 0) {
		WithFormButtonsBar *withFormButtonsBar = [[WithFormButtonsBar alloc] initWithFrame:CGRectMake(0, 0, self.width, withFormButtonsBarHeight)];
		withFormButtonsBar.tag = -8888;
		[withFormButtonsBar addWithFormButtons:withFormButtons buttonCol:buttonCol delegate:self];
		self.tableview.tableFooterView = withFormButtonsBar;
		[withFormButtonsBar release];
	}
	if ([[formLayoutCopy objectForKey:@"slc"] count] > 0) {
		MCSectionBar *sectionBar = (MCSectionBar *)[self.clientView viewWithTag:-321];
		if (nil == sectionBar) {
			sectionBar = [[MCSectionBar alloc] initWithFrame:CGRectMake(0, 0, self.width, nToolBarHeight)];
			sectionBar.autoresizingMask = nMCViewAutoresizingMask;
			sectionBar.tag = - 321;
			[sectionBar addSectionBar:[formLayoutCopy objectForKey:@"lbl"] withItems:[formLayoutCopy objectForKey:@"slc"] delegate:self];
			[self.clientView addSubview:sectionBar];
			[sectionBar release];	
		}else {
			[sectionBar refreshFrame:CGRectMake(0, 0, self.width, nToolBarHeight) itemsCount:[[formLayoutCopy objectForKey:@"stn"] count]+1];
		}
	}
}

- (void)dealloc {
	[dataObjectName release];
	[layoutName release];
	[keyValue release];
	[initialValues release];
	[formData release];
	[formLayout release];
	if (listCell) {
		[listCell release];listCell = nil;
	}
	[viewButtons release];
	[subButtons release];
	[imageSizeMap release];imageSizeMap = nil;
	[backgroundView release];
	[formLayoutCopy release];
	[formDataCopy release];
	[withFormButtons release];
	[super dealloc];
}

#pragma mark ---- 数据加载方法 ----
- (void)getDataFromServer {
	[[MServerDAO sharedInstance] getFormDataAsync:self.dataObjectName
									   layoutName:self.layoutName 
											  key:self.keyValue
									   isEditable:@"0"
										 delegate:self];
}

#pragma mark -- MCServer2ViewDelegate --
- (void)getDataFromServerSuccess: (NSMutableDictionary *)returnValue {
	self.formData = returnValue;
	tabIndex = 0;
	
	NSMutableDictionary *datas = [self.formData objectForKey:@"data"];
	if (datas == nil){ 
		datas = [NSMutableDictionary dictionary];
		[self.formData setObject:datas forKey:@"data"];
	}
	NSMutableArray *sections = [formLayoutCopy objectForKey:@"stn"];
	if (sections != nil) {
		for(int i = 0; i < [sections count]; i++){
			NSMutableDictionary *section = [sections objectAtIndex:i];
			NSMutableArray *appItems = [section objectForKey:@"item"];
			for(int j = 0; j < [appItems count]; j++){
				NSMutableDictionary *appItem = [appItems objectAtIndex:j];
				
				NSString *name = [MCUIToolkit getFieldName:appItem];			
				NSString *fieldType = [MCUIToolkit getFieldType:appItem];
				
				NSMutableDictionary *fieldData = [datas objectForKey:name];
				if (fieldData == nil) {
					fieldData = [NSMutableDictionary dictionary];
					[fieldData setObject:@"" forKey:@"value"];
					[datas setObject:fieldData forKey:name];
				}
				if (![fieldData objectForKey:@"lbl"] || [@"" isEqualToString:[fieldData objectForKey:@"lbl"]]) {
					if([fieldType isEqualToString: @"3"] || [fieldType isEqualToString: @"4"] || [fieldType isEqualToString: @"U"]){
						NSString *relationObject = [MCUIToolkit getRelationObject:appItem];
						if(relationObject != nil && ![relationObject isEqualToString:@""]
						   && nil != [fieldData objectForKey:@"value"] && ![@"" isEqualToString:[fieldData objectForKey:@"value"]]){
							id relReturnObject = [[MServerDAO sharedInstance] getFormData:relationObject layoutName:@"" key:[fieldData objectForKey:@"value"] isEditable:@"1"];
							if(relReturnObject){
								NSMutableDictionary *relObject = (NSMutableDictionary *)relReturnObject;
								if ([relObject objectForKey:@"desc"]) 
									[fieldData setObject:[relObject objectForKey:@"desc"] forKey:@"lbl"];
							}
						}
					}
				}
				
				// 置表单数据的强制赋值
				for (int l = 0; l < [self.initialValues count]; l++) {
					NSMutableDictionary *initialValue = [self.initialValues objectAtIndex:l];
					if ([[initialValue objectForKey:@"fld"] isEqualToString:name]) {
						[initialValue setObject:@"init"forKey:@"flag"];
						if([initialValue objectForKey:@"value"] == nil){
							break;
						}
						[fieldData setObject:[initialValue objectForKey: @"value"] forKey:@"value"];
						[datas setObject:fieldData forKey:name];
						if([fieldType isEqualToString: @"3"] || [fieldType isEqualToString: @"4"] || [fieldType isEqualToString: @"U"]){
							NSString *relationObject = [MCUIToolkit getRelationObject:appItem];
							NSMutableArray *lookupBackFills = [appItem objectForKey: @"lpbf"];
							if(relationObject != nil && ![relationObject isEqualToString:@""]
							   && nil != [fieldData objectForKey:@"value"] && ![@"" isEqualToString:[fieldData objectForKey:@"value"]]){
								if (![fieldData objectForKey:@"lbl"] || lookupBackFills != nil) {
									id relReturnObject = [[MServerDAO sharedInstance] getFormData:relationObject layoutName:@"" key:[fieldData objectForKey:@"value"] isEditable:@"1"];
									if(relReturnObject){
										NSMutableDictionary *relObject = (NSMutableDictionary *)relReturnObject;
										if (![fieldData objectForKey:@"lbl"])
											[fieldData setObject:[relObject objectForKey:@"desc"] == nil?@"":[relObject objectForKey:@"desc"] forKey:@"lbl"];
										NSMutableDictionary *relDatas = [NSMutableDictionary dictionary];
										if ([relObject objectForKey:@"data"]){ 
											relDatas = [relObject objectForKey:@"data"];
										}
										
										if (lookupBackFills != nil) {
											for(int k = 0; k<[lookupBackFills count]; k++){
												NSMutableDictionary *lookupBackFill = [lookupBackFills objectAtIndex:k];
												NSString *fieldName = [lookupBackFill objectForKey:@"bf"];
												NSMutableDictionary *fieldDataLookupBack = [relDatas objectForKey:fieldName];
												[self setLookupBackFillByFieldName: [lookupBackFill objectForKey:@"fld"] fieldDataLookupBack:fieldDataLookupBack];	
											}
										}
									}
								}
							}
						}			
						break;
					}
				}	
			}
		}
	}	
	for(int m = 0; m < [self.initialValues count]; m++){
		NSMutableDictionary *initialValue = [initialValues objectAtIndex:m];
		if (![initialValue objectForKey:@"flag"]) {
			NSMutableDictionary *initialData = [NSMutableDictionary dictionary];
			[initialData setObject:[initialValue objectForKey:@"value"] == nil?@"":[initialValue objectForKey:@"value"] forKey:@"value"];
			[datas setObject:initialData forKey:[initialValue objectForKey:@"fld"]];
		}
	}
	if (formDataCopy) {
		[formDataCopy release];formDataCopy = nil;
	}
	formDataCopy = [[MCUIToolkit getObjectCopy:self.formData] retain];
	if (sections != nil) {
		for(int i = 0; i < [sections count]; i++){
			NSMutableDictionary *section = [sections objectAtIndex:i];
			NSMutableArray *appItems = [section objectForKey:@"item"];
			for(int j = 0; j < [appItems count]; j++){
				NSMutableDictionary *appItem = [appItems objectAtIndex:j];
				NSString *fieldType = [MCUIToolkit getFieldType:appItem];
				NSMutableDictionary *datas = [formDataCopy objectForKey:@"data"];
				NSString *fieldName = [[MCUIToolkit getFieldName:appItem] retain];
				NSMutableDictionary *fieldData = [datas objectForKey:fieldName];
				if ([fieldData objectForKey:@"v"]) {
					if ([[fieldData objectForKey:@"v"] boolValue] == NO) {
						[appItems removeObjectAtIndex:j];
						j--;
						continue;
					}
				}
				
				if ([@"Y" isEqualToString:fieldType]) {
					NSMutableArray *fileInfos = [fieldData objectForKey:@"fi"];
					if (fileInfos != nil) {
						if ([fileInfos count] > 0) {
							for (int k = 0; k < [fileInfos count]; k++) {
								NSMutableDictionary *fileInfo = [fileInfos objectAtIndex:k];
								NSMutableDictionary *fileInfoCopy = [MCUIToolkit getObjectCopy:fileInfo];
								NSMutableDictionary *appItemCopy = [MCUIToolkit getObjectCopy:appItem];
								NSMutableDictionary *field = [MCUIToolkit getField:appItemCopy];
								[field setObject:@"J" forKey:@"type"];
								if (k != 0) {
									[field setObject:@"" forKey:@"lbl"];
								}
								[field setObject:[NSString stringWithFormat:@":copy:%@%d",fieldName, k] forKey:@"name"];
								[appItems insertObject:appItemCopy atIndex:j];
								j++;
								NSMutableDictionary *fieldDataCopy = [MCUIToolkit getObjectCopy:fieldData];
								NSMutableArray *fileInfosCopy = [fieldDataCopy objectForKey:@"fi"];
								[fileInfosCopy removeAllObjects];
								[fileInfosCopy addObject:fileInfoCopy];
								[datas setObject:fieldDataCopy forKey:[NSString stringWithFormat:@":copy:%@%d",fieldName, k]];
								
							}
							[appItems removeObjectAtIndex:j];
							j--;
							[datas removeObjectForKey:fieldName];
							continue;
						}
					}
				}	
				int  lableStyle = [[appItem objectForKey:@"lbls"] intValue];
				if (lableStyle == 2) {
					NSString *fieldValue = [MCUIToolkit getFieldTextValue:formDataCopy
																  appItem:appItem
															 selectOption:[formDataCopy objectForKey:@"so"]];
					if([fieldValue length] == 0){
						[appItems removeObjectAtIndex:j];
						j--;
						continue;
					}
				}
			}
		}
	}
	
	//动态表单标签
	if ([returnValue objectForKey:@"csty"]) {
		NSMutableDictionary *csty = [returnValue objectForKey:@"csty"];
		if ([csty objectForKey:@"label"]) {
			self.title = [csty objectForKey:@"label"];
		}
	}
	
	[self createRightBarButton];
	[self.tableview reloadData];
}


#pragma mark ---- UITableView方法 ----
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	if(isSectionTab) {
		return 1;
	}
	
	return [[formLayoutCopy objectForKey:@"stn"] count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
	if(isSectionTab) {
		return 0;
	}
	
	if ([[[formLayoutCopy objectForKey:@"stn"] objectAtIndex:section] objectForKey:@"lbl"] == nil ||
		[@"" isEqualToString:[[[formLayoutCopy objectForKey:@"stn"] objectAtIndex:section] objectForKey:@"lbl"]]
		||[[formLayoutCopy objectForKey:@"stn"] count] <= 1) {
		return 0;
	}	
	return 30;
}

- (NSInteger) cellHeight:(int)lableStyle 
			   withTitle:(NSString*)aTitle 
			   withValue:(NSString*)aValue
			 withAppItem:(NSMutableDictionary *)aAppItem

{
	return [MCFunction cellHeight:lableStyle withTitle:aTitle withValue:aValue withAppItem:aAppItem];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	int sectionIndex = indexPath.section;
	if (isSectionTab) {
		sectionIndex = tabIndex;
	}
	NSMutableDictionary *appItem = [[[[formLayoutCopy objectForKey:@"stn"] 
									  objectAtIndex:sectionIndex]//indexPath.section
									 objectForKey:@"item"]
									objectAtIndex:indexPath.row];
	int  lableStyle = [[appItem objectForKey:@"lbls"] intValue];
	NSString* aTitle = [MCUIToolkit getFieldLabel:appItem];
	NSString* aValue = [MCUIToolkit getFieldTextValue:formDataCopy
											  appItem:appItem
										 selectOption:[formDataCopy objectForKey:@"so"]];
	
	NSString *fieldType = [MCUIToolkit getFieldType:appItem];
	char cFieldType;
	strncpy(&cFieldType, [fieldType UTF8String], 1);
	if (cFieldType == 'S') {
		NSString *name = [MCUIToolkit getFieldName:appItem];
		NSMutableDictionary *fieldData = [[formDataCopy objectForKey:@"data"] objectForKey:name];
		NSMutableArray *fileInfos = [fieldData objectForKey:@"fi"];
		if (fileInfos == nil || [fileInfos count] < 1) 
			return [self cellHeight:lableStyle withTitle:aTitle withValue:aValue withAppItem:appItem];
		NSMutableDictionary *fileInfo = [fileInfos objectAtIndex:0];
		NSString *fileName = [NSString stringWithFormat:@"indexPath_Seciton%d_Row%d_%@", indexPath.section,
							  indexPath.row, [fileInfo objectForKey:@"fname"]];
		MCSize *size = [imageSizeMap objectForKey:fileName];
		if (size && size.height > 0) {
			if (lableStyle > 0) {
				if (lableStyle == 1) { //标题换行
					return size.height+50;
				} else {//标题隐藏
					return size.height+20;
				}
//				if (size.width < 300.0) {
//					return size.height+20;
//				}else {
//					return size.height/(size.width/300.0)+20;
//				}
			}else {
				if (size.width < 200.0) {
					return size.height+20;
				}else {
					return size.height/(size.width/200.0)+20;
				} 			}
		}
	} else if (cFieldType == '0') {
		NSString* size= [imageSizeMap objectForKey:[NSString stringWithFormat:@"WebViewSize-section:%d-row:%d", indexPath.section, indexPath.row]];
		if (size) {
			NSArray *array = [size componentsSeparatedByString:@":"];
			if ([array count] == 2) {
				return [[array objectAtIndex:1] floatValue] + 20;
			}
		}
		//return CGRectGetHeight(clientView.frame) / 3 + 10;
	}
	
	return [self cellHeight:lableStyle withTitle:aTitle withValue:aValue withAppItem:appItem];
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger) section {
	if ([[formLayoutCopy objectForKey:@"stn"] count] > 1) {
		UILabel *sectionHead = [[[UILabel alloc] init] autorelease];
		sectionHead.textAlignment = UITextAlignmentCenter;
		sectionHead.text = [[[formLayoutCopy objectForKey:@"stn"] objectAtIndex:section] objectForKey:@"lbl"];
		sectionHead.font = [UIFont boldSystemFontOfSize:20];
		sectionHead.textColor = [UIColor whiteColor];
		sectionHead.backgroundColor = [UIColor colorWithPatternImage:self.userDefaults.skin_bgSectionImg];
		return sectionHead;
	} else {
		return nil;
	}
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	if (isSectionTab) {
		return [[[[formLayoutCopy objectForKey:@"stn"] objectAtIndex:tabIndex] objectForKey:@"item"] count]; 
	}
	
	return [[[[formLayoutCopy objectForKey:@"stn"] objectAtIndex:section] objectForKey:@"item"] count];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
	return [[[formLayoutCopy objectForKey:@"stn"] objectAtIndex:section] objectForKey:@"lbl"] ;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	int sectionIndex = indexPath.section;
	if (isSectionTab) {
		sectionIndex = tabIndex;
	}
	
	// 主表单
	NSMutableDictionary *appItem = [[[[formLayoutCopy objectForKey:@"stn"] 
									  objectAtIndex:sectionIndex]//indexPath.section
									 objectForKey:@"item"]
									objectAtIndex:indexPath.row];
	
	UITableViewCell *cell = [MCFunction createCellForViewForm:tableView 
													  appItem:appItem
													indexPath:indexPath 
													 formView:self.clientView];  
    
	NSString *fieldType = [MCUIToolkit getFieldType:appItem];
	char cFieldType;
	strncpy(&cFieldType, [fieldType UTF8String], 1);
	
	UILabel *labelField = (UILabel *)[cell.contentView viewWithTag:-1];
	labelField.text = [MCUIToolkit getFieldLabel:appItem];
	//NSLog(@"---------text=%@,type=%c----", labelField.text,cFieldType);
	if (cFieldType != 'S') {
		NSString *valueText = [[MCUIToolkit getFieldTextValue:formDataCopy
													  appItem:appItem
												 selectOption:[formDataCopy objectForKey:@"so"]] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
		
		if (cFieldType == '0') {
			@try {
				UIWebView *webView = (UIWebView *)[cell.contentView viewWithTag:-2];
				if (nil != valueText && ![@"" isEqualToString: valueText]) {
					webView.delegate = self;
					[webView loadHTMLString:valueText baseURL:nil];
				}
				return cell;
			}
			@catch (NSException * e) {
			}
		}
		UILabel *valueField = (UILabel *)[cell.contentView viewWithTag:-2];
		NSMutableDictionary *style = [appItem objectForKey:@"style"];
		if (style != nil) {
			float fontSize = 16.0;
			if ([style objectForKey:@"font_color"]) {
				valueField.textColor = [MCFunction hexColor:[NSString stringWithFormat:@"%@64", [style objectForKey:@"font_color"]]];
			}
			if ([style objectForKey:@"font_size"]) {
				fontSize = [[style objectForKey:@"font_size"] floatValue]/0.75;
				valueField.font = [UIFont boldSystemFontOfSize:fontSize];
			}
			if ([style objectForKey:@"font_style"]) {
				NSString *fontStyle = [style objectForKey:@"font_style"];
				if ([fontStyle isEqualToString:@"B"]) {
					valueField.font = [UIFont boldSystemFontOfSize:fontSize];
				}else if ([fontStyle isEqualToString:@"I"]) {
					valueField.font = [UIFont italicSystemFontOfSize:fontSize];
				}else {
					valueField.font = [UIFont boldSystemFontOfSize:fontSize];
				}
			}
			if ([style objectForKey:@"font_align"]) {
				NSString *fontAlign = [style objectForKey:@"font_align"];
				if ([fontAlign isEqualToString:@"L"]) {
					valueField.textAlignment = UITextAlignmentLeft;
				}else if ([fontAlign isEqualToString:@"R"]) {
					valueField.textAlignment = UITextAlignmentRight;
				}else if ([fontAlign isEqualToString:@"M"]) {
					valueField.textAlignment = UITextAlignmentCenter;
				}
			}
		}
		
		if (cFieldType == 'H'||cFieldType == 'I'||cFieldType == 'K'||cFieldType == 'L') {
			NSArray *selectIcons = [valueText componentsSeparatedByString:@"::"];
			if ([selectIcons count] > 1) {
				NSString *iconLabel = [selectIcons objectAtIndex:1];
				NSArray *icons = [iconLabel componentsSeparatedByString:@","];
				for (int j = 0; j < [icons count]; j++) {
					NSString *icon = [icons objectAtIndex:j];
					UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(32 * j, 0, 24, 24)];
					imageView.image = [MCFunction scaleAndRotateImage:[UIImage imageNamed:icon] width:24.0 height:24.0];
					imageView.backgroundColor = [UIColor clearColor];
					[valueField addSubview:imageView];
					[imageView release];
				}
				return cell;
			} 
		}
		//超级链接，链接地址为空，不跳转
		if (cFieldType == '5') {
			if ([valueText length] == 0) {
				cell.accessoryType = UITableViewCellAccessoryNone;
			} else {
				cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
			}
		}
		valueField.text = [valueText stringByReplacingOccurrencesOfString:@"&nbsp;" withString:@""];
		[valueField sizeToFit];
	} else {
		NSString *name = [MCUIToolkit getFieldName:appItem];
		NSMutableDictionary *fieldData = [[formDataCopy objectForKey:@"data"] objectForKey:name];
		NSString *dataFrom = [fieldData objectForKey:@"df"] == nil?@"":[fieldData objectForKey:@"df"];
		NSMutableArray *fileInfos = [fieldData objectForKey:@"fi"];
		if (fileInfos == nil || [fileInfos count] < 1) 
			return cell;
		NSMutableDictionary *fileInfo = [fileInfos objectAtIndex:0];
		NSString *fileName = [fileInfo objectForKey:@"fname"];
		if (fileName == nil || [fileName length] == 0)
			return cell;
		NSString *fileLocation = [fileInfo objectForKey:@"lcn"];
		
		NSMutableDictionary *fileAttribute = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
											  fileName,@"fileName",
											  fileLocation,@"fileLocation",
											  @"download",@"actionType",
											  dataFrom,@"dataFrom",
											  [NSString stringWithFormat:@"%d", indexPath.section], @"indexPath_section",
											  [NSString stringWithFormat:@"%d", indexPath.row], @"indexPath_row",
											  nil];
		
		MCImageView *valueField = (MCImageView *)[cell.contentView viewWithTag:-2];
		
		NSMutableDictionary *field = [MCUIToolkit getField:appItem];
		if([field objectForKey:@"imgw"] && [field objectForKey:@"imgh"]) {
			valueField.imgw = [[field objectForKey:@"imgw"] intValue];;
			valueField.imgh = [[field objectForKey:@"imgh"] intValue];
		}
		
		if (valueField.image == nil) {
			valueField.fileAttribute = fileAttribute;
			[fileAttribute release];
		}else {
			int lableStyle = [[appItem objectForKey:@"lbls"] intValue];
			if (lableStyle > 0) {
				if (valueField.image.size.width < 300) {
					valueField.frame = CGRectMake(10, lableStyle==1?40:10, valueField.image.size.width, 35);
				}
			}else {
				if (valueField.image.size.width < 200) {
					valueField.frame = CGRectMake(110, lableStyle==1?40:10, valueField.image.size.width, 35);
				}
			}
		}
		
	}
	
	
	return cell;
}	

-(void)changeSection:(id)sender {
	[self onFormSelected:[sender selectedSegmentIndex]];
}

- (void)onFormSelected:(int)index
{
	tabIndex = index;
	[self createRightBarButton];
	
	if (index == 0 || isSectionTab) {
		[self.clientView bringSubviewToFront:self.tableview];
		[self.tableview reloadData];
	}
	else {
		// 子表单
		DataGridComponentDataSource *ds = [[DataGridComponentDataSource alloc] init];
		NSMutableArray *titleWidth = [NSMutableArray array];
		NSMutableArray *titleLabel = [NSMutableArray array];
		NSMutableArray *fieldTypes = [NSMutableArray array];
		NSMutableArray *listFields = [[[formLayoutCopy objectForKey:@"slc"] 
									   objectAtIndex:index - 1]
									  objectForKey:@"item"];
		
		int itemCount = 0;
		for(int i = 0;i < [listFields count];i++) {
			if ([[[listFields objectAtIndex:i] objectForKey:@"v"] boolValue]) {
				itemCount++;
			}
		}
		int j = -1;
		NSString *subDataObjectName = [[[formLayoutCopy objectForKey:@"slc"] 
										objectAtIndex:index-1]
									   objectForKey:@"dto"];
		for(int i = 0;i < [listFields count];i++) {
			if ([[[listFields objectAtIndex:i] objectForKey:@"v"] boolValue]) {
				
				NSString *label = [MCUIToolkit getFieldLabel:[listFields objectAtIndex:i]];
				[titleLabel addObject:label];
				j++;
				int length = MAX([MCUIToolkit getFieldLength:[listFields objectAtIndex:i]]*8.0, 
								 [MCUIToolkit getMaxWidth:[[[formDataCopy objectForKey:@"sdata"] objectForKey:subDataObjectName] objectForKey:@"rl"]
											 withAppItems:[listFields objectAtIndex:i]]);
				//				int length = [MCUIToolkit getFieldLength:[listFields objectAtIndex:i]];
				//				if (itemCount == 1){
				//					length = 40;
				//				}
				//				if (itemCount == 2){
				//					length = 40 / 2;
				//				}
				//				if (length == 0) {
				//					length = 15;
				//				}
				//				length = length * 8;
				
				NSString *len = [NSString stringWithFormat:@"%d",length];
				NSString *fieldType = [MCUIToolkit getFieldType:[listFields objectAtIndex:i]];
				[titleWidth addObject:len];
				[fieldTypes addObject:fieldType];
			}
		}
		
		ds.columnWidth = titleWidth;
		ds.titles = titleLabel;
		ds.fieldTypes = fieldTypes;
		//数据行＝＝＝＝＝＝＝＝
		
		NSMutableArray *tableValue = [NSMutableArray array];
		
		NSMutableArray *recordList = [[[formDataCopy objectForKey:@"sdata"] objectForKey:subDataObjectName] objectForKey:@"rl"];
		
		for (int row = 0; row < [recordList count]; row++) {
			//填充数据=============
			NSMutableDictionary *record = [recordList objectAtIndex:row];
			
			NSMutableArray *rowData = [[NSMutableArray alloc] init];
			for (int i = 0;i < [listFields count] ; i++) {
				if ([[[listFields objectAtIndex:i] objectForKey:@"v"] boolValue]) {
					
					NSString *strValue = [MCUIToolkit getFieldTextValue:record 
																appItem:[listFields objectAtIndex:i]
														   selectOption:nil];
					
					if (strValue == nil) {
						strValue = @"";
					}
					[rowData addObject:strValue];
				}
			}
			[tableValue addObject:rowData];
			[rowData release];
		}
		ds.data = tableValue;
		
		if (listCell != nil) {
			[listCell removeFromSuperview];
			[listCell release];
		}
		listCell = [[[[MCUserDefaults instance] class:@"ListCell"] alloc] initWithFrame:self.tableview.frame 
																				   data:ds 
																			   gridType:@"S"
																			  totalPage:0
																			currentPage:0 
																	 isFirstColumnFixed:NO
																				 isMsel:NO];
		listCell.dataObjectName = subDataObjectName;
		listCell.layoutName = self.layoutName;
		listCell.listLayout = formLayoutCopy;
		listCell.listData = recordList;
		listCell.tabIndex = index;
		listCell.viewController = self;
		[ds release];
		[self.clientView addSubview:listCell];
	}
}

- (void)onTableViewElementSelected:(NSIndexPath *)indexPath {
	int section = [indexPath section];
	if(isSectionTab) {
		section = tabIndex;
	}
	
	int row = [indexPath row];
	NSMutableDictionary *appItem = [[[[formLayoutCopy objectForKey:@"stn"] 
									  objectAtIndex:section]
									 objectForKey:@"item"]
									objectAtIndex:row];
	
	NSString *name = [MCUIToolkit getFieldName:appItem];
	NSString *fieldType = [MCUIToolkit getFieldType:appItem];
	
	NSMutableDictionary *datas = [formDataCopy objectForKey:@"data"];
	
	NSMutableDictionary *fieldData = [datas objectForKey:name];
	if (fieldData == nil) {
		fieldData = [NSMutableDictionary dictionary];
		if ([fieldType isEqualToString:@"J"] || 
			[fieldType isEqualToString:@"S"] || 
			[fieldType isEqualToString:@"Y"]) {
			NSMutableArray *fileInfos = [NSMutableArray array];
			[fieldData setObject:fileInfos forKey:@"fi"];
			[fieldData setObject:@"" forKey:@"df"];
			[datas setObject:fieldData forKey:name];
		}
		else {
			[fieldData setObject:@"" forKey:@"value"];
			[datas setObject:fieldData forKey:name];
		}
	}
	
	
	[self.tableview deselectRowAtIndexPath:indexPath animated:YES];
	[MCFunction selectDetailForViewForm:self
							   withCell:[self.tableview cellForRowAtIndexPath:indexPath]
						  withIndexPath:indexPath
								appItem:appItem 
								   data:[datas objectForKey:name]];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
	if (cell.accessoryType != UITableViewCellAccessoryDisclosureIndicator) {
		[tableView deselectRowAtIndexPath:indexPath animated:YES];
		return;
	}
	[self onTableViewElementSelected:indexPath];
}

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath*)indexPath {
	[self onTableViewElementSelected:indexPath];
}

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item {
	[self onFormSelected:item.tag];
}

- (void) createRightBarButton {
	if (tabIndex == 0 || isSectionTab) {
		
		// 生成主表单的操作入口按钮
		
		NSMutableArray *cfgButtons = [formLayoutCopy objectForKey:@"btn"];
		NSMutableArray *dataButtons = [formDataCopy objectForKey:@"btn"];
		if (viewButtons) {
			[viewButtons release]; viewButtons = nil;
		}
		viewButtons = [[MCUIToolkit getButtons:dataButtons cfgButtons:cfgButtons] retain];
		if (!withFormButtons) {
			withFormButtons = [MCUIToolkit getWithFormButtons:viewButtons];
			int withFormButtonsBarHeight = [MCUIToolkit getWithFormButtonsBarHeight:withFormButtons buttonCol:buttonCol];
			if (withFormButtonsBarHeight != 0) {
				WithFormButtonsBar *withFormButtonsBar = [[WithFormButtonsBar alloc] initWithFrame:CGRectMake(0, 0, self.width, withFormButtonsBarHeight)];
				withFormButtonsBar.tag = -8888;
				[withFormButtonsBar addWithFormButtons:withFormButtons buttonCol:buttonCol delegate:self];
				self.tableview.tableFooterView = withFormButtonsBar;
				[withFormButtonsBar release];
			}
		}
		
		// 生成表单按钮
		[self rightBarButton:@"操作" withStyle:UIBarButtonItemStyleDone selector:@selector(selectAction:)];
		if ([viewButtons count] == 1) {
			
			self.rightBarButtonItemTitle = [[viewButtons objectAtIndex:0] objectForKey:@"lbl"];
		}
		else if ([viewButtons count] > 1) {
			self.rightBarButtonItemTitle = @"操作";
		}else {
			self.rightBarButtonItem = nil;
		}
	}
	else {
		
		NSString *subDataObjectName = [[[formLayoutCopy objectForKey:@"slc"] 
										objectAtIndex:tabIndex - 1]
									   objectForKey:@"dto"];
		
		NSMutableArray *cfgButtons = [[[formLayoutCopy objectForKey:@"slc"] objectAtIndex:tabIndex-1] objectForKey:@"btn"];
		NSMutableArray *dataButtons = [[[formDataCopy objectForKey:@"sdata"] objectForKey:subDataObjectName] objectForKey: @"btn"];
		
		subButtons = [[MCUIToolkit getButtons:dataButtons cfgButtons:cfgButtons] retain];
		[self rightBarButton:@"操作..." withStyle:UIBarButtonItemStyleDone selector:@selector(selectAction:)];
		if ([subButtons count] == 1) {
			self.rightBarButtonItemTitle = [[subButtons objectAtIndex:0] objectForKey:@"lbl"];
		}
		else if ([subButtons count] > 1) {
			self.rightBarButtonItemTitle = @"操作...";
		}else {
			self.rightBarButtonItem = nil;
		}	
	}
}

- (void) setLookupBackFillByFieldName: (NSString *)fieldName fieldDataLookupBack:(NSMutableDictionary *)fieldDataLookupBack {	
	NSMutableDictionary *datas = [formData objectForKey:@"data"];
	NSMutableArray *sections = [formLayoutCopy objectForKey:@"stn"];
	if (sections != nil) {
		for(int i = 0; i < [sections count]; i++){
			NSMutableDictionary *section = [sections objectAtIndex:i];
			NSMutableArray *appItems = [section objectForKey:@"item"];
			for(int j = 0; j < [appItems count]; j++){
				NSMutableDictionary *appItem = [appItems objectAtIndex:j];
				NSString *name = [MCUIToolkit getFieldName:appItem];			
				NSString *fieldType = [MCUIToolkit getFieldType:appItem];
				
				if ([fieldName isEqualToString:name]) {
					if (![fieldDataLookupBack objectForKey:@"lbl"] || [[fieldDataLookupBack objectForKey:@"lbl"] isEqualToString:@""]) {
						if([fieldType isEqualToString: @"3"] || [fieldType isEqualToString: @"4"] || [fieldType isEqualToString: @"U"]){
							NSString *relationObject = [MCUIToolkit getRelationObject:appItem];
							if(relationObject != nil && ![relationObject isEqualToString:@""]){
								id relReturnObject = [[MServerDAO sharedInstance] getFormData:relationObject layoutName:@"" key:[fieldDataLookupBack objectForKey:@"value"] isEditable:@"1"];
								if(relReturnObject){
									NSMutableDictionary *relObject = (NSMutableDictionary *)relReturnObject;
									[fieldDataLookupBack setObject:[relObject objectForKey:@"desc"] == nil?@"":[relObject objectForKey:@"desc"] forKey:@"lbl"];
								}
							}
						}
					}
					[datas setObject:fieldDataLookupBack forKey:name];
				}
			}
		}
	}
	[self.tableview reloadData];
}

#pragma mark ---- 事件处理方法 ----

- (void)withFormButtonsAction:(id) sender {
	NSMutableDictionary *button = [withFormButtons objectAtIndex:((UIButton *)sender).tag];
	if ([MCErrorManagement showAuthMessage:button]) {
		return;
	}
	NSString *buttonId = [button objectForKey:@"id"] == nil?@"":[button objectForKey:@"id"];
	NSMutableDictionary *parameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
									   buttonId,@"buttonId",
									   @"view_form",@"buttonType",
									   self.dataObjectName,@"dataObjectName",
									   self.formData,@"formData", nil];
	
	if ([button objectForKey:@"cfmi"] != nil && ![[button objectForKey:@"cfmi"] isEqualToString:@""]){
		[MCFunction pushViewByUrl:[button objectForKey:@"url"] 
					   parameters:parameters 
				   confirmMessage:[button objectForKey:@"cfmi"]
				   naviController:self.navigationController];
	}else{
		[MCFunction pushViewByUrl:[button objectForKey:@"url"] 
					   parameters:parameters 
				   confirmMessage:nil
				   naviController:self.navigationController];
	}
	[parameters release];		
}


- (void) selectAction: (id) sender {	
	UIActionSheet *menu;
	
	if (tabIndex == 0 || isSectionTab) {
		if ([viewButtons count] == 1) {
			NSMutableDictionary *button = [viewButtons objectAtIndex:0];
			if ([MCErrorManagement showAuthMessage:button]) {
				return;
			}
			NSString *buttonId = [button objectForKey:@"id"] == nil?@"":[button objectForKey:@"id"];
			NSMutableDictionary *parameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
											   buttonId,@"buttonId",
											   @"view_form",@"buttonType",
											   self.dataObjectName,@"dataObjectName",
											   self.formData,@"formData", nil];
			
			if ([button objectForKey:@"cfmi"] != nil && ![[button objectForKey:@"cfmi"] isEqualToString:@""]){
				[MCFunction pushViewByUrl:[button objectForKey:@"url"] 
							   parameters:parameters 
						   confirmMessage:[button objectForKey:@"cfmi"]
						   naviController:self.navigationController];
			}else{
				[MCFunction pushViewByUrl:[button objectForKey:@"url"] 
							   parameters:parameters 
						   confirmMessage:nil
						   naviController:self.navigationController];
			}
			[parameters release];
			return;
		}
		
		//导航bar上面的操作按钮弹出菜单
		menu = [MCUIToolkit actionSheet:viewButtons
								withTag:0
						   withDelegate:self
							  withTitle:@"选择操作"];
		[menu showFromTabBar:(UITabBar *)[self.navigationController view]];
	}
	else {
		NSString *subDataObjectName = [[[formLayoutCopy objectForKey:@"slc"] 
										objectAtIndex:tabIndex-1]
									   objectForKey:@"dto"];
		if ([subButtons count] == 1) {
			// 响应明细表单的表单按钮
			NSMutableDictionary *button = [subButtons objectAtIndex:0];
			if ([MCErrorManagement showAuthMessage:button]) {
				return;
			}
			NSString *buttonId = [button objectForKey:@"id"] == nil?@"":[button objectForKey:@"id"];
			NSMutableDictionary *record = [[formDataCopy objectForKey:@"sdata"] objectForKey:subDataObjectName];
			
			NSMutableDictionary *url = [button objectForKey:@"url"];
			NSMutableDictionary *parameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
											   buttonId,@"buttonId",
											   @"list_form",@"buttonType",
											   subDataObjectName,@"dataObjectName",
											   record,@"formData",nil];
			[MCFunction pushViewByUrl:url 
						   parameters:parameters
					   confirmMessage:[[button objectForKey:@"comfirm"] boolValue]?[button objectForKey:@"comfirmString"]:nil
					   naviController:self.navigationController];
			[parameters release];
			return;			
		}
		// 弹出明细表单的表单按钮
		menu = [MCUIToolkit actionSheet:subButtons
								withTag:0
						   withDelegate:self
							  withTitle:@"选择操作"];
		actionSheetFlag = -1;
		[menu showFromTabBar:(UITabBar *)[self.navigationController view]];
	}
}

- (void) selectCancelAction: (id) sender {
	[self.navigationController popViewControllerAnimated:YES];
}

- (void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
	if (tabIndex == 0 || isSectionTab) {
		// 响应主表单的表单按钮
		if (buttonIndex == [viewButtons count]) {
			// 按下取消按钮
			return;
		}
		NSMutableDictionary *button = [viewButtons objectAtIndex:buttonIndex];
		if ([MCErrorManagement showAuthMessage:button]) {
			return;
		}
		NSString *buttonId = [button objectForKey:@"id"] == nil?@"":[button objectForKey:@"id"];
		NSMutableDictionary *parameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
										   buttonId,@"buttonId",
										   @"view_form",@"buttonType",
										   self.dataObjectName,@"dataObjectName",
										   self.formData,@"formData", nil];
		
		if ([button objectForKey:@"cfmi"] != nil && ![[button objectForKey:@"cfmi"] isEqualToString:@""]){
			[MCFunction pushViewByUrl:[button objectForKey:@"url"] 
						   parameters:parameters 
					   confirmMessage:[button objectForKey:@"cfmi"]
					   naviController:self.navigationController];
		}else{
			[MCFunction pushViewByUrl:[button objectForKey:@"url"] 
						   parameters:parameters 
					   confirmMessage:nil
					   naviController:self.navigationController];
		}
		[parameters release];		
	}
	else {
		if (actionSheetFlag == -1) {
			// 响应明细表单的表单按钮
			if (buttonIndex == [subButtons count]) {
				// 按下取消按钮
				return;
			}
			NSString *subDataObjectName = [[[formLayoutCopy objectForKey:@"slc"] 
											objectAtIndex:tabIndex-1]
										   objectForKey:@"dto"];
			
			NSMutableDictionary *record = [[formDataCopy objectForKey:@"sdata"] objectForKey:subDataObjectName];
			
			NSMutableDictionary *listLayoutButton = [subButtons objectAtIndex:buttonIndex];
			NSString *buttonId = [listLayoutButton objectForKey:@"id"] == nil?@"":[listLayoutButton objectForKey:@"id"];
			NSMutableDictionary *url = [listLayoutButton objectForKey:@"url"];
			NSMutableDictionary *parameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
											   buttonId,@"buttonId",
											   @"list_form",@"buttonType",
											   subDataObjectName,@"dataObjectName",
											   record,@"formData",nil];
			[MCFunction pushViewByUrl:url 
						   parameters:parameters
					   confirmMessage:[[listLayoutButton objectForKey:@"comfirm"] boolValue]?[listLayoutButton objectForKey:@"comfirmString"]:nil
					   naviController:self.navigationController];
			[parameters release];
		}
	}
}

#pragma mark ---处理接收到的消息---
//- (void) getImageSize:(id)anObject
- (void)getImageSize:(NSNotification *)notification
{
	MCSize* size = [notification object];
	
	[imageSizeMap setObject:size forKey:size.filename];
	[size release];
	[self.tableview reloadData];
}

//数据加载完
- (void)webViewDidFinishLoad:(UIWebView *)webView {
	if (![webView isKindOfClass:[MCWebView class]]) {
		return;
	}
	MCWebView* mcWebView = (MCWebView*)webView;
	NSString* key = [NSString stringWithFormat:@"WebViewSize-section:%d-row:%d", mcWebView.section, mcWebView.row];
	if ([imageSizeMap objectForKey:key]) {
		return;
	}
	//NSString *stringText = [webView :@"document.body.text;"];
	//NSLog(@"------%@", stringText);
	
//	CGSize actualSize = [webView sizeThatFits:CGSizeZero];
//    CGRect newFrame = webView.frame;
//	newFrame.size.height = actualSize.height + 10;
//    webView.frame = newFrame;
	
	NSString *string = [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.clientHeight;"/*@"document.body.scrollHeight;"*/];
    CGRect frame = [webView frame];
    frame.size.height = [string floatValue] - 40;
    [webView setFrame:frame];   
	
	CGSize size = webView.bounds.size;
	
	[imageSizeMap setObject:[NSString stringWithFormat:@"%f:%f",size.width, size.height] forKey:key];
	
	[self.tableview reloadData];
}

@end
